package offer;

import java.util.Stack;

public class offerII_0038 {
    public int[] dailyTemperatures(int[] temperatures) {
        int len=temperatures.length;
        Stack<int[]> stack=new Stack<>();
        int[] result=new int[len];
        for(int i=len-1;i>=0;--i){
            if(stack.isEmpty()){
                result[i]=0;
                stack.push(new int[]{temperatures[i],i});
            }
            else if(stack.peek()[0]<=temperatures[i]){
                while(!stack.isEmpty()&&stack.peek()[0]<=temperatures[i]){
                    stack.pop();
                }
                if(stack.isEmpty()){
                    stack.push(new int[] {temperatures[i],i});
                    result[i]=0;
                }
                else{
                    result[i]=stack.peek()[1]-i;
                    stack.push(new int[] {temperatures[i],i});
                }
            }
            else{
                result[i]=stack.peek()[1]-i;
                stack.push(new int[] {temperatures[i],i});
            }
        }
        return result;
    }
}
